package pkg

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/base64"
	"fmt"
	"log"
	"strconv"
	"strings"
	"time"
	"xiaoniu-task/pkg/req"
)

// GenSign 根据时间戳和签名获取sign
func GenSign(secret string, timestamp int64) (string, error) {
	//timestamp + key 做sha256, 再进行base64 encode
	stringToSign := fmt.Sprintf("%v", timestamp) + "\n" + secret

	var data []byte
	h := hmac.New(sha256.New, []byte(stringToSign))
	_, err := h.Write(data)
	if err != nil {
		return "", err
	}

	signature := base64.StdEncoding.EncodeToString(h.Sum(nil))
	return signature, nil
}

// SendText 通过群机器人发送消息
func SendText(url string, content string, secret string) (bool, error) {
	params := make(map[string]interface{})
	timeStamp := time.Now().Unix()
	sign, err := GenSign(secret, timeStamp)
	if err != nil {
		log.Println("sign生成出错：", err.Error())
		return false, err
	}

	params["timestamp"] = strconv.FormatInt(timeStamp, 10)
	params["sign"] = sign
	params["msg_type"] = "text"
	textBody := make(map[string]string)
	textBody["text"] = content
	params["content"] = textBody

	res, err := req.PostJson(url, params)
	if err != nil {
		return false, err
	}
	//{
	//	"Extra": null,
	//	"StatusCode": 0,
	//	"StatusMessage": "success"
	//}
	return strings.Contains(res, "success"), nil
}
